package com.ming.elm.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ming.elm.dao.DeliveryAddressDao;
import com.ming.elm.po.DeliveryAddress;
import com.ming.elm.service.DeliveryAddressService;
import com.ming.elm.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

public class DeliveryAddressServiceImpl implements DeliveryAddressService{

	@Override
	public List<DeliveryAddress> listDeliveryAddressByUserId(String userId) {
		List<DeliveryAddress> list = new ArrayList<>();
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		DeliveryAddressDao mapper = sqlSession.getMapper(DeliveryAddressDao.class);
		try {
			list = mapper.listDeliveryAddressByUserId(userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		sqlSession.close();
		return list;
	}
	
	@Override
	public int saveDeliveryAddress(DeliveryAddress deliveryAddress) {
		int result = 0;
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		DeliveryAddressDao mapper = sqlSession.getMapper(DeliveryAddressDao.class);
		try {
			result = mapper.saveDeliveryAddress(deliveryAddress);
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		} finally {
			sqlSession.commit();
			sqlSession.close();
		}
		return result;
	}
	
	@Override
	public DeliveryAddress getDeliveryAddressById(Integer daId) {
		DeliveryAddress data = null;
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		DeliveryAddressDao mapper = sqlSession.getMapper(DeliveryAddressDao.class);
		try {
			data = mapper.getDeliveryAddressById(daId);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
		return data;
	}
	
	@Override
	public int updateDeliveryAddress(DeliveryAddress deliveryAddress) {
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		DeliveryAddressDao mapper = sqlSession.getMapper(DeliveryAddressDao.class);
		int result = 0;
		try {
			result = mapper.updateDeliveryAddress(deliveryAddress);
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		} finally {
			sqlSession.commit();
			sqlSession.close();
		}

		return result;
	}
	
	@Override
	public int removeDeliveryAddress(Integer daId) {

		SqlSession sqlSession = MybatisUtil.getSqlSession();
		DeliveryAddressDao mapper = sqlSession.getMapper(DeliveryAddressDao.class);
		int result = 0;
		try {
			result = mapper.removeDeliveryAddress(daId);
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		} finally {
			sqlSession.commit();
			sqlSession.close();
		}

		return result;
	}
}
